package 热题100;

public class Num4_findMedianSortedArrays {
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {

        int m1 = nums1.length;
        int m2 = nums2.length;
        if(nums1.length == 0 && nums2.length == 0){
            return 0;
        }else if(nums1.length == 0){
           if(m2 % 2 == 0){
               return nums2[m2 / 2];
           }else{
               double n1 = nums2.length;
               return (double) ( nums2[(int)(n1 / 2)] + nums2[(int)((n1 / 2) + 0.5)] ) / 2;
           }
        }else if(nums2.length == 0){
            if(m1 % 2 == 0){
                return nums1[m1 / 2];
            }else{
                double n2 = nums1.length;
                return (double) ( nums1[(int)(n2 / 2)] + nums1[(int)((n2 / 2) + 0.5)] ) / 2;
            }
        }

        int n = m1 + m2;
        int rep = 0;

        int tmp = 0;//指向当前数组的下标位置
        int left1 = 0;
        int left2 = 0;

        for (int i = 0; i < n / 2; i++) {
            if(nums1[left1] <= nums2[left2]){
                rep = nums1[left1];
               if(left1 < nums1.length - 1) left1 ++;
            }else{
                rep = nums2[left2];
                if(left2 < nums2.length - 1)  left2 ++;
            }
        }
        if(nums2[left2] > nums1[left1]){
           if(left1 == m1 - 1 && left2 != m2 - 1){
               rep += nums2[left2];
           }else{
               rep += nums1[left1];
           }
        }else{
            rep += nums2[left2];
        }


        return  (double) rep / 2;
    }

    public static void main(String[] args) {

        Num4_findMedianSortedArrays num4 = new Num4_findMedianSortedArrays();
        int[] arr1 = {1,3};
        int[] arr2 = {2,7};
        double a = num4.findMedianSortedArrays(arr1,arr2);
        System.out.println(a);
    }
}
